import time
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import unittest

class TestAdminCouples(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Edge()
        self.driver.implicitly_wait(10)
        self.base_url = 'http://127.0.0.1:5000'

    def tearDown(self):
        if hasattr(self, 'driver'):
            self.driver.quit()

    def _login_admin(self):
        """管理员登录的辅助方法"""
        self.driver.get(f'{self.base_url}/login')
        time.sleep(1)

        username_input = self.driver.find_element(By.ID, 'username_or_email')
        username_input.send_keys('admin')

        password_input = self.driver.find_element(By.ID, 'password')
        password_input.send_keys('123456')

        submit_button = self.driver.find_element(By.CLASS_NAME, 'btn')
        submit_button.click()
        time.sleep(1)

    def test_add_couple(self):
        """测试添加新爱人功能"""
        # 登录管理员账号   qq575732022
        self._login_admin()

        # 导航到添加爱人页面
        self.driver.get(f'{self.base_url}/admin/couples')
        time.sleep(1)

        # 填写表单
        # 基本信息
        self.driver.find_element(By.ID, 'season').send_keys('1')
        self.driver.find_element(By.ID, 'marriage_years').send_keys('5')

        # 丈夫信息
        self.driver.find_element(By.ID, 'husband_name').send_keys('测试丈夫')
        self.driver.find_element(By.ID, 'husband_age').send_keys('30')
        self.driver.find_element(By.ID, 'husband_occupation').send_keys('工程师')
        time.sleep(2)

        # 修改图片路径获取方式
        current_dir = os.path.dirname(os.path.abspath(__file__))
        project_root = os.path.dirname(current_dir)  # 获取项目根目录
        test_image_path = os.path.join(project_root, 'tests', 'app', 'static', 'images', 'default_avatar.jpg')

        # 确保图片文件存在
        if not os.path.exists(test_image_path):
            raise FileNotFoundError(f"测试图片不存在: {test_image_path}")

        # 使用JavaScript来设置文件输入的值
        husband_avatar = self.driver.find_element(By.ID, 'husband_avatar')
        self.driver.execute_script(
            "arguments[0].style.display = 'block';",
            husband_avatar
        )
        husband_avatar.send_keys(os.path.abspath(test_image_path))

        # 妻子信息
        self.driver.find_element(By.ID, 'wife_name').send_keys('测试妻子')
        self.driver.find_element(By.ID, 'wife_age').send_keys('28')
        self.driver.find_element(By.ID, 'wife_occupation').send_keys('设计师')

        # 使用相同的图片作为妻子头像
        wife_avatar = self.driver.find_element(By.ID, 'wife_avatar')
        self.driver.execute_script(
            "arguments[0].style.display = 'block';",
            wife_avatar
        )
        wife_avatar.send_keys(os.path.abspath(test_image_path))

        time.sleep(1)  # 给文件上传一些时间

        # 故事简介
        self.driver.find_element(By.ID, 'story').send_keys('这是一对测试夫妻的故事...')
        time.sleep(2)

        # 修改提交表单按钮的选择器，使用更具体的选择器
        submit_button = self.driver.find_element(
            By.CSS_SELECTOR, 
            '.admin-form button[type="submit"]'
        )
        submit_button.click()
        time.sleep(2)

        # 验证是否添加成功
        try:
            WebDriverWait(self.driver, 5).until(
                EC.url_contains('/admin/couples')
            )
            page_source = self.driver.page_source
            self.assertIn('测试丈夫', page_source)
            self.assertIn('测试妻子', page_source)
        except TimeoutException:
            self.fail("添加爱人失败，页面未正确跳转")

if __name__ == '__main__':
    unittest.main() 